//$(function(){
useCloudDoc = function (url, docName) {
    showblockUI();
    var postData = "url=" + url + "&fileInputFileName=" + docName + "&type=1" + '&edit=' + (new Date()).valueOf();
    var docId = 0;
	var wi = window.open('about:blank', '_blank');
	wi.document.write("服务器正在处理中，请稍后……")
	wi.blur();
    $.ajax({
        url: 'sign!upload.xml',
        type: 'POST',
        data: postData,
        dataType: 'xml',
        error: function () {
            closeAlert();
        },
        success: function (data) {
            var result = $(data).find("result >resultMsg").text();
            if (result == null || result == "") {
                showAlert("系统出错，请稍后重试");
                return;
            }
            var jsonData = JSON.parse(result);
            var errCode = jsonData["errCode"];
            if (errCode > 0) {
                var errShow = new Boolean(jsonData["errShow"]);
                if (errShow == true) {
                    showAlert(jsonData["msg"]);
                } else {
                    showAlert("系统出错，请稍后重试");
                }
                return;
            } else {
                closeAlert();
                docId = jsonData["docId"];
                //location.href = "sign!page?skip=writeContract&signdocId=" + jsonData["docId"];
            }
			wi.location.href = "sign!page?skip=writeContract&signdocId=" + docId;
			wi.focus();
        }
    });
}

getCloudDoc = function (startIndex) {
    $("#cloudFileTb").html("");
    $("#pageDiv").html("");
    var docName = $("#docName").val();
    var postData = "type=3" + "&docName=" + docName + "&startIndex=" + startIndex + "&pageSize=7" + '&edit=' + (new Date()).valueOf();
    $.ajax({
        url: 'doc!getDocList.xml',
        type: 'POST',
        data: postData,
        dataType: 'xml',
        error: function () {

        },
        success: function (data) {
            var result = $(data).find("result >resultMsg").text();
            if (result == null || result == "") {
                showAlert("系统出错，请稍后重试");
                return;
            }
            var jsonData = JSON.parse(result);
            var errCode = jsonData["errCode"];
            if (errCode > 0) {
                var errShow = new Boolean(jsonData["errShow"]);
                if (errShow == true) {
                    showAlert(jsonData["msg"]);
                } else {
                    showAlert("系统出错，请稍后重试");
                }
                return;
            } else {
                var items = jsonData["docs"];
                if (null != items) {
                    $("#noCloud").show()
                    if (Object.prototype.toString.call(items) != '[object Array]') {
                        var one = items;
                        var items = new Array();
                        items[0] = one;
                    }
                    $("#noCloud").hide();
                    $(items).each(function (index) {
                        $("#cloudFileTb").append("<tr>"
                            + "<td height='28' class='bord5'>" + items[index]["docId"] + ".</td>"
                            + "<td class='bord5'><a onclick='javascript:useCloudDoc(\"" + items[index]["url"] + "\", \"" + items[index]["docName"] + "\")' style='color: #e74031;cursor:pointer;' href='javascript:void(0)'>" + items[index]["docName"] + "</a></td>"
                            + "<td class='bord5'><a onclick='javascript:useCloudDoc(\"" + items[index]["url"] + "\", \"" + items[index]["docName"] + "\")' style='color: green;cursor:pointer;'  href='javascript:void(0)'>发送</a></td>"
                            + "</tr>");
                    });
                    var curPage = jsonData["pageInfo"]["curPage"];
                    var indexesLength = jsonData["pageInfo"]["indexes"].length;
                    if (curPage > 1) {
                        $("#pageDiv").append("<a class='active' href='javascript:getCloudDoc(" + jsonData["pageInfo"]["previousIndex"] + ")'>上一页</a>");
                    }
                    if (curPage < indexesLength) {
                        $("#pageDiv").append("<a class='active' href='javascript:getCloudDoc(" + jsonData["pageInfo"]["nextIndex"] + ")'>下一页</a>");
                    }
                } else {
                    $("#noCloud").show();
                }
            }
            showFancybox('cloudFile');
        }
    });
}

//获取文件数量
getCount = function () {
    var postData = "edit=" + (new Date()).valueOf();
    $.ajax({
        url: 'doc!getDocCount.xml',
        type: 'POST',
        data: postData,
        dataType: 'xml',
        error: function () {

        },
        success: function (data) {
            var result = $(data).find("result >resultMsg").text();
            if (result == null || result == "") {
                showAlert("系统出错，请稍后重试");
                return;
            }
            var jsonData = JSON.parse(result);
            var errCode = jsonData["errCode"];
            if (errCode > 0) {
                var errShow = new Boolean(jsonData["errShow"]);
                if (errShow == true) {
                    showAlert(jsonData["msg"]);
                } else {
                    showAlert("系统出错，请稍后重试");
                }
                return;
            } else {
                $("#waitForMeCount").text(jsonData["waitForMeCount"]);
                $("#waitForTaCount").text(jsonData["waitForTaCount"]);
                $("#draftCount").text(jsonData["draftCount"]);
                $("#doneCount").text(jsonData["doneCount"]);
                $("#cloudCount").text(jsonData["cloudCount"]);
                $("#closeCount").text(jsonData["closeCount"]);
                $("#sendbackCount").text(jsonData["sendbackCount"]);
                $("#iSendbackCount").text(jsonData["iSendbackCount"]);
                $("#otherSendbackCount").text(jsonData["otherSendbackCount"]);
            }
        }
    });
}
getOssFile = function (docId, items) {
    $("#ossFile").html("");
    showFancybox('ossFileList');
    if (null != items) {
        if (Object.prototype.toString.call(items) != '[object Array]') {
            var one = items;
            var items = new Array();
            items[0] = one;
        }

        $(items).each(function (index) {
            if (items[index]["isRead"] == 1) {
                $("#ossFile").append("<tr>"
                    + "<td height='28' class='bord5'>" + items[index]["sender"] + "</td>"
                    + "<td class='bord5'>" + items[index]["receiver"] + "</td>"
                    + "<td class='bord5'><a onclick='javascript:downloadDoc(" + docId + ", \"" + items[index]["receiverUUID"] + "\")' style='cursor:pointer;color: green;'>下载</a></td>"
                    + "</tr>");
            } else {
                if (items[index]["type"] == 1) {
                    $("#ossFile").append("<tr>"
                        + "<td height='28' class='bord5'>" + items[index]["sender"] + "</td>"
                        + "<td class='bord5'>" + items[index]["receiver"] + "</td>"
                        + "<td class='bord5'><a onclick='javascript:downloadDoc(" + docId + ", \"" + items[index]["receiverUUID"] + "\")' style='cursor:pointer;color: green;'>仅接收</a></td>"
                        + "</tr>");
                } else {
                    $("#ossFile").append("<tr>"
                        + "<td height='28' class='bord5'>" + items[index]["sender"] + "</td>"
                        + "<td class='bord5'>" + items[index]["receiver"] + "</td>"
                        + "<td class='bord5'><a>未签署</a></td>"
                        + "</tr>");
                }
            }
        });
    }
}

showReceivers = function (items) {
    if (null != items) {
        if (Object.prototype.toString.call(items) != '[object Array]') {
            var one = items;
            var items = new Array();
            items[0] = one;
        }
        var contentHtml = "<table class='table'><thead><th>发件人</th><th>收件人</th><th>签署状态</th></thead>";
        $(items).each(function (index) {
            var reveiver = items[index]["receiver"];
            if ("" != items[index]["receiverName"]) {
                reveiver = items[index]["receiverName"];
            }
            var isRead = "";
            if (items[index]["type"] == 1) {
                isRead = "仅接收";
            } else if (items[index]["isRead"] == 0) {
                isRead = "未签署";
            } else if (items[index]["isRead"] == 1) {
                isRead = "已签署";
            }
            //senderName和sender两个字段优先选择senderName
            var senderName=items[index]["senderName"];
            if(senderName=="" || senderName==null){
                senderName=items[index]["sender"];
            }
            contentHtml += "<tr>"
                + "<td class='textL'>" + senderName + "</td>"
                + "<td class='textL'>" + reveiver + "</td>"
                + "<td class='textL'>" + isRead + "</td>"
                + "</tr>";
        });
        contentHtml += "</table>";
        $.bootstrapDialog({
            title: "收件人列表",
            message: contentHtml,
        });

    }
}
//删除文档
deleteDoc = function (docId) {
    $.stopPropagation();
    closeAlert();
    var postData = "docId=" + docId + '&edit=' + (new Date()).valueOf();
    $.ajax({
        url: 'doc!deleteDoc.xml',
        type: 'POST',
        data: postData,
        dataType: 'xml',
        error: function () {

        },
        success: function (data) {
            var result = $(data).find("result >resultMsg").text();
            if (result == null || result == "") {
                showAlert("系统出错，请稍后重试");
                return;
            }
            var jsonData = JSON.parse(result);
            var errCode = jsonData["errCode"];
            if (errCode > 0) {
                var errShow = new Boolean(jsonData["errShow"]);
                if (errShow == true) {
                    showAlert(jsonData["msg"]);
                } else {
                    showAlert("系统出错，请稍后重试");
                }
                return;
            } else {
                resetTableContent(DoclistViewer.option.type);
            }
        }
    });
    return false;
}
//只读文档查看
onlyWatchSubmit = function (id, sends, signType,returnType) {
    sessionStorage.removeItem("currentDocListFirst");
    sessionStorage.setItem("currentDocListFirst", JSON.stringify({
        docId: id,
        sends: sends,
    }));
    $.stopPropagation();
    $("#skip").val("onlyWatch");
    $("#signdocId").val(id);
    $("#returnType").val(returnType);
    $("#sends").val(JSON.stringify(sends));
    $("#next").submit();
}
//下载文档
downloadDoc = function (docId, accountUid, eleId) {
    var postData = "docId=" + docId + "&accountUid=" + accountUid + '&edit=' + (new Date()).valueOf();
    $.ajax({
        url: 'doc!downloadDoc.xml',
        type: 'POST',
        data: postData,
        async: false,
        dataType: 'xml',
        error: function () {

        },
        success: function (data) {
            var result = $(data).find("result >resultMsg").text();
            if (result == null || result == "") {
                showAlert("系统出错，请稍后重试");
                return;
            }
            var jsonData = JSON.parse(result);
            var errCode = jsonData["errCode"];
            if (errCode > 0) {
                var errShow = new Boolean(jsonData["errShow"]);
                if (errShow == true) {
                    showAlert(jsonData["msg"]);
                } else {
                    showAlert("系统出错，请稍后重试");
                }
                return;
            } else {
            	//更新标记
            	var tagTd = $(eleId).closest('tr').children()[3];
            	if (!$(tagTd).children('div').children('div .down-tag')[0]) {
            		$(tagTd).children('div').prepend("<div class='down-tag'><div class='tag-close' name='tag' tag='down' docid=" + docId + "></div></div>");
            		$("div[name='tag']").tooltip({
            			title: '删除',
            		});
            		$("div[name='tag']").bind('click', function(){
            			$('.loading').show();
            			var tagParent = $(this).parent('div');
            			var tag = "-" + $(this).attr('tag');
            			var docId = $(this).attr('docid');
            			var postData = "docId=" + docId + "&optType=0&url=&reason=&tag=" + tag;
            			$.ajax({
            				url: 'doc!updateDoc.xml',
            				type: 'POST',
            				data: postData,
            				async: false,
            				dataType: 'xml',
            				error: function () {
            					setTimeout(function(){$('.loading').hide();}, 500);
            				},
            				success: function (data) {
            					setTimeout(function(){$('.loading').hide();}, 500);
            					tagParent.remove();
            				}
            			});
            		});
            	}
            	window.open(jsonData["downUrl"], '_blank');
            }
        }
    });
}

operationDoc = function (docId, optType, url) {
    var reason = $("#reasonContent").val();
    reason = $.trim(reason);
    if (optType == 5 && reason == "") {
        $(".alert").show();
        return;
    }

    var postData = "docId=" + docId + "&optType=" + optType + "&url=" + url + "&reason=" + reason + "&edit=" + (new Date()).toString();
    $.ajax({
        url: 'doc!updateDoc.xml',
        type: 'POST',
        data: postData,
        async: false,
        dataType: 'xml',
        error: function () {

        },
        success: function (data) {
            $(".close").click();
            var result = $(data).find("result >resultMsg").text();
            if (result == null || result == "") {
                showAlert("系统出错，请稍后重试");
                return;
            }
            var jsonData = JSON.parse(result);
            var errCode = jsonData["errCode"];
            if (errCode > 0) {
                var errShow = new Boolean(jsonData["errShow"]);
                if (errShow == true) {
                    showAlert(jsonData["msg"]);
                } else {
                    showAlert("系统出错，请稍后重试");
                }
                return;
            } else {
                DoclistViewer.refresh();
                if (optType == 5) {
                    window.location.href = "../user/doc!page?skip=doclist-view&type=10";
                } else if (optType == 3) {
                    showAlert("已通过短信或邮件的方式通知对方及时完成签署。");
                } else if (optType == 6) {
                    showAlert("已关闭文件签署");
                    resetTableContent(11);

                }
            }
        }
    });
}
//显示退回原因
showBackReason = function (reason) {
    $.bootstrapDialog({
        title: "退回原因",
        message: "<div class='dialog-content p14'>" + reason + "</div>"
    })
}

//显示文档流程
signLog = function (docId) {
    $.stopPropagation();
    var postData = "docId=" + docId + "&edit=" + (new Date()).valueOf();
    $.ajax({
        url: 'sign!signLog.xml',
        type: 'POST',
        data: postData,
        dataType: 'xml',
        error: function () {

        },
        success: function (data) {
            var result = $(data).find("result >resultMsg").text();
            if (result == null || result == "") {
                showAlert("系统出错，请稍后重试");
                return;
            }
            var jsonData = JSON.parse(result);
            var errCode = jsonData["errCode"];
            if (errCode > 0) {
                var errShow = new Boolean(jsonData["errShow"]);
                if (errShow == true) {
                    showAlert(jsonData["msg"]);
                } else {
                    showAlert("系统出错，请稍后重试");
                }
                return;
            } else {
                var items = jsonData["optlogs"];
                items = sort(items);
                var contentHtml = "<div class='dialog-content'>";
                $(items).each(function (index) {
                    var one = items[index];
                    var appendHtml = "<div class='oneAccount'><div class='accountHead'>";
                    var imgHtml = "untreated.png";
                    var optType = "未处理";
                    if (one["opt"] == 0) {
                        imgHtml = "untreated.png";
                        optType = "未处理";
                    } else if (one["opt"] == 1) {
                        imgHtml = "initiate.png";
                        optType = "发起签署";
                    } else if (one["opt"] == 2) {
                        imgHtml = "ok.png";
                        optType = "已签署";
                    } else if (one["opt"] == 4) {
                        imgHtml = "ok.png";
                        optType = "重新发起签署";
                    }
                    else if (one["opt"] == 5) {
                        imgHtml = "returned.png";
                        optType = "退回文件";
                    } else if (one["opt"] == 6) {
                        imgHtml = "returned.png";
                        optType = "关闭文件";
                    }
                    appendHtml += "<img  src='../images_2.0/" + imgHtml + "'>";
                    appendHtml += "<span>" + one["name"] + "(" + optType + ")</span>";
                    appendHtml += "</div><div class='signLogContent'>"
                    if (one["createDate"] != undefined) {
                        appendHtml += "<span>操作时间：" + one["createDate"] + "</span>";
                    }
                    appendHtml += "</div></div>";
                    contentHtml += appendHtml;
                });
                contentHtml += "</div>";
                $.bootstrapDialog({
                    title: "文件签署",
                    message: contentHtml,
                    //size: BootstrapDialog.SIZE_SMALL
                })
            }
        }
    });
}
//显示退回操作
showSendBack = function (docId, optType, url, name) {
    $.stopPropagation();
    $.bootstrapDialog({
        title: "文档退回",
        CustomData: {recieverName: name},
        message: $("<div class='dialog-content'></div>").load("../dialog/doclist/sendBack.html"),
        onshown: function (dialog) {
            var timer = setInterval(function(){
               if($("#submitSendBack").length > 0){
                   $("#submitSendBack").on("click", function () {
                       operationDoc(docId, optType, url);
                   })
                   clearInterval(timer)
               }
            },100)
        }
    });

}
var EnoughPay = function(){
    function Impl(){

    }
    Impl.payResult = [];
    var cache_Uid = new Array();
    Impl.getResult = function(docId){
        return Impl.payResult[docId];
    }
    Impl.addResult = function(payMethod, senderUUid){
        //payMethod 0：发起人付，1：各自付
        var accountUid = senderUUid;
        if(payMethod == 1){
            accountUid =  accountUid =  sessionStorage.getItem("session_accountUid");;
        }
        if(cache_Uid.indexOf(accountUid) > -1){
            return ;
        }
        cache_Uid.push(accountUid);
        $.TsignAjax({
            url:"../user/account!getBillingRemain.xml",
            data:"accountId=" + accountUid,
                async:false,
            success:function(jsonData){
                if(!jsonData["data"]["sumInfo"]){
                    Impl.payResult[accountUid] = "-1";
                    return ;
                }
                Impl.payResult[accountUid] = jsonData["data"]["sumInfo"]["remain"];
                },
                error:function(jsonData){
                    Impl.payResult[accountUid] = "failed";
                }
            }
        )
    }
    return Impl;
}();

/**
 *继续签署操作，判断账户是否余额不足
 * @param signDoc 文档id
 * @param nextType 返回标记
 * @param senderUUid 发件人uid
 * @param payMethod 付费方式（0\发起人付，1\各自付款）
 * @param sender
 * @param receiverUUID 接收者uid
 */
isEnoughPay = function (signDoc, nextType, senderUUid, payMethod, sender) {
    var accountUid = senderUUid;
    var flag = "发起者";
    if(payMethod == 1){
        accountUid =  sessionStorage.getItem("session_accountUid");
        flag = "您"
    }
    $.stopPropagation();
    //签署次数足够
    if(parseInt(EnoughPay.getResult(accountUid)) > 0){
        signWaitForMe(signDoc, nextType, senderUUid, payMethod, sender);
    }else{
        if(EnoughPay.getResult(accountUid) == -1){
            showAlert(flag+"还未订购任何计费套餐");
            return;
        }
        if(EnoughPay.getResult(accountUid) == "failed"){
            showAlert("计费服务异常");
            return;
        }
        if(payMethod == 1){
            shouldRecharge(null);
        }else{
            shouldRecharge(sender);
        }
    }
}
/*messageHanddle = function (args) {
    if (remains > 0) {
        signWaitForMe(args);
    } else {
        if (args[3] == 1) {
            shouldRecharge(null);
        } else {
            shouldRecharge(args[4]);
        }
    }
}*/
function getNextType(sends) {
    var nextType = 2;
    if (sends.length > 1) {
        var read = 0;
        $(sends).each(function (index) {
            if (sends[index]["isRead"] == 0) {
                read++;
            }
        });
        if (read > 1) {
            nextType = 5;
        }
    }

    return nextType;
}

sort = function (arr) {
    for (var i = 0; i < arr.length; i++) {
        for (var j = 0; j < arr.length - i - 1; j++) {
            if (arr[j]["createTime"] > arr[j + 1]["createTime"]) {
                var t = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = t;
            }
        }
    }
    return arr;
}
//更新表格内容
resetTableContent = function (type) {
    DoclistViewer.option.type = type;
  //  DoclistViewer.refresh({query: {type: type}});
    DoclistViewer.refreshOptions({
        type: type,
        pageNumber:1,
    })

}

function getTag() {
	var tags = '';
	$('div[name="selectTag"][tag="1"]').each(function(){
		tags += $(this).attr('v') + ',';
	});
	debugger;
	return tags;
}
//
searchDoc = function () {
    var docInfo = {
        receiver: $.trim($("#receiveName").val()),
        docName: $.trim($("#docName").val()),
        sender: $.trim($("#senderName").val()),
        startDate: $.trim($("#startDate").val()),
        endDate: resetDate($("#endDate").val(),1),
        tag: getTag()
    }
    DoclistViewer.refreshOptions({
        docBean:JSON.stringify(docInfo),
        pageSize: $(".select-pagination .btn-warning").attr("data-size")
    })
}
resetSearch = function(){
    $("#search input").val("");
    $('div[name="selectTag"]').each(function(){
    	var className = $(this).attr('class');
    	$(this).removeClass(className);
		$(this).addClass(className.split('-')[0] + '-' + className.split('-')[1]);
		$(this).attr('tag', "0");
    });
    $('div[name="tag-action"]').each(function(){
    	var className = $(this).attr('class');
    	$(this).removeClass(className);
		$(this).addClass(className.split('-')[0] + '-' + className.split('-')[1] + '-selected');
		$(this).attr('tag', "0");
    });
    searchDoc();
}
//变更菜单状态
resetTitActive = function (type) {
    $(".tit").removeClass("on");
    $(".rebackShow").removeClass("rebackShow");
    if (!(type == 10 || type == 12 || type == 13)) {
        $("#li10_1").slideUp();
        $("#li10_2").slideUp();
    }
    onId = "#li1";
    if (type == 5) {
        onId = "#li2";
    } else if (type == 2) {
        onId = "#li3";
    } else if (type == 1) {
        onId = "#li4";
    } else if (type == 3) {
        onId = "#li5";
    } else if (type == 10) {
        onId = "#li10"
        $("#li10_1").slideDown();
        $("#li10_2").slideDown();
        $("#li10_1").find("a").css("color", "#6c6c6c");
        $("#li10_2").find("a").css("color", "#6c6c6c");
    } else if (type == 11) {
        onId = "#li11"
    }
    if (type == 12) {
        $("#li10_2").addClass("rebackShow");
        onId = "#li10";
        $("#li10_1").find("a").css("color", "#6c6c6c");
        $("#li10_2").find("a").css("color", "#e74031");
    } else if (type == 13) {
        $("#li10_1").addClass("rebackShow");
        onId = "#li10";
        $("#li10_1").find("a").css("color", "#e74031");
        $("#li10_2").find("a").css("color", "#6c6c6c");
    }
    $(onId).attr("class", "tit on");
    if (type == 3) {
        $("div[data-btn-type='single']").show()
        $("div[data-btn-type='group']").hide();
        return ;
    }
    $("div[data-btn-type='group']").show();
    $("div[data-btn-type='single']").hide()

}
showCloudDoc = function () {
    $.bootstrapDialog({
        title: "云文件签署",
        message: $("<div></div>").load("../dialog/doclist/cloud-list.html"),
        onshown: function () {

        }
    });
}
showModalSelect = function(){
    $.bootstrapDialog({
        title:"合同模板选择",
        message:$("<div></div>").load("../dialog/doclist/doc-modal.html")
    })
}
//用于绑定页面事件
initListenerAction = function () {
    //$(".local-sign").bind("click",function(){
    //    $("#fileInput").click();
    //    return false;
    //});
    $(".cloud-sign").bind("click",function(){
        showCloudDoc();
        return false;
    });
    $(".modal-sign").bind("click",function(){
        showModalSelect();
        return false;
    });
}
$(function(){
    initListenerAction();
})
//    });
//类型判断
function fillTypeContent(type, row) {
    if (type == 3) {
        return "<img src='../images_2.0/fasong1_51.png' class='pr5'>云文件";
    }
    //1: 草稿
    else if (type == 1) {
        return "<img src='../images_2.0/fasong1_51.png' class='pr5'>草稿";
    } else {
        var sends = row["sends"];
        if (sends.length == 1) {
            var signType = "仅接收";
            //sends.type 签署类型
            //0: only one　单独签
            if (sends[0]["type"] == 0) {
                signType = "签署";
            }
            //2: onebyone　顺序
            else if (sends[0]["type"] == 2) {
                signType = "会签";
            }
            //else 1: 仅接收(可能还有类型４: keyword)
            return "<img src='../images_2.0/fasong1_51.png' class='pr5'>" + signType;
        }
        //sends == 0 ,理论上只会出现在草稿箱、已完成,认证签／快截签不添加接收者的时候
        //sends > 1 会签(顺序签)
        else {
            return "<img src='../images_2.0/fasong1_51.png' class='pr5'>会签";
        }
    }
}
/*signWaitForMe = function () {
    var arg = arguments[0];
    sessionStorage.signType = 'me';
    $.TsignSubmit({
        url: "sign!page",
        input: [{name: "skip", value: "ownerSign"},
            {name: "page", value: "receive"},
            {name: "signdocId", value: arg[0]},
            {name: "nextType", value: arg[1]},
            {name: "payMethod", value: arg[3]},
            {name: "sender", value: arg[4]}
        ],
        target: "_blank"
    });
}
writeContractSubmit = function (id, sends, signType,event) {
    var flag = signType == undefined ? "normal" : "change"
    $.TsignSubmit({
        url: "sign!page",
        target: "_blank",
        input: {skip: "writeContract", : id, sends: JSON.stringify(sends), signType: flag}
    }, true)
}*/
signWaitForMe = function (signDoc, nextType, senderUUid, payMethod, sender) {
    //var doc = {
    //    "docId":signDoc,
    //    "nextType":nextType,
    //    "payMethod":payMethod,
    //    "sender":sender,
    //    "pageType":"receive"
    //}
    //sessionStorage.setItem(signDoc,JSON.stringify(doc));
    //window.open("sign!page?skip=ownerSign2&docId="+signDoc);
    sessionStorage.signType = 'me';
    $("#SignWaitForMeForm input[name='signdocId']").val(signDoc);
    $("#SignWaitForMeForm input[name='nextType']").val(nextType);
    $("#SignWaitForMeForm input[name='payMethod']").val(payMethod);
    $("#SignWaitForMeForm input[name='sender']").val(sender);
    $("#SignWaitForMeForm").submit();
}
writeContractSubmit = function (id, sends, signType) {
    var flag = signType == undefined ? "normal" : "change"
    $("#WriteContractSubmit input[name='signdocId']").val(id);
    $("#WriteContractSubmit input[name='sends']").val(JSON.stringify(sends));
    $("#WriteContractSubmit input[name='signType']").val(flag);
    $("#WriteContractSubmit").submit();
}
createFormWriteContractSubmit = function(){
    $.TsignSubmit({
        url: "sign!page",
        formName:"WriteContractSubmit",
        isSubmit:false,
        target: "_blank",
        input: {skip: "writeContract", signdocId: "", sends:"", signType: ""}
    }, true)
}
createFormSignWaitForMe = function(){
    $.TsignSubmit({
        url: "sign!page",
        formName:"SignWaitForMeForm",
        isSubmit:false,
        input: [{name: "skip", value: "ownerSign"},
            {name: "page", value: "receive"},
            {name: "signdocId", value: ""},
            {name: "nextType", value: ""},
            {name: "payMethod", value: ""},
            {name: "sender", value: ""}
        ],
        target: "_blank"
    });
}
//操作判断
fillOptionContent = function (type, row) {
    var accountUUID = sessionStorage.getItem("session_accountuid");
    //解决原因换行正确显示问题
    var reason = row["reason"];
    reason = reason != undefined ? reason.replace(/[\r\n]/g, "<br>") : reason;
    createFormWriteContractSubmit();
    createFormSignWaitForMe();
    var appendHtml = "";
    appendHtml += "<div class='dropDownList' style='display:block'><ul>";

    //1: 草稿
    if (type == 1) {
        appendHtml += "<li><a class='' onclick='javascript:writeContractSubmit(" + row["docId"] + ", " + JSON.stringify(row["sends"]) + ");'  href='javascript:void(0)'>继续</a></li>"
        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showEventChoose(\"确认删除文档\", \"deleteDoc(" + row["docId"] + ")\");''>删除</a></li>";

    }
    //2: 已完成
    else if (type == 2) {
        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:downloadDoc(" + row["docId"] + ", \"\", " + "this" + ")'>下载</a></li>";
        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showEventChoose(\"确认删除文档\", \"deleteDoc(" + row["docId"] + ")\");' >删除</a></li>";
    }
    //3: 云文件
    else if (type == 3) {
        appendHtml += "<li><a class='' onclick='javascript:useCloudDoc(\"" + row["url"] + "\", \"" + row["docName"] + "\")' href='javascript:void(0)'>发送</a></li>";
        appendHtml += "<li><a class='' href='javascript:void(0)'  onclick='javascript:showEventChoose(\"确认删除文档\", \"deleteDoc(" + row["docId"] + ")\");'>删除</a></li>";
    }
    //4: 待我签
    else if (type == 4) {
        var sender = row["sends"][0]["senderName"] == "" ? row["sends"][0]["sender"] : row["sends"][0]["senderName"];
        var nextType = getNextType(row["sends"]);
        EnoughPay.addResult(row["payMethod"],row["sends"][0]["senderUUID"]);
        appendHtml += "<li><a class='' onclick='javascript:isEnoughPay(" + row["docId"] + "," + nextType + ",\"" + row["sends"][0]["senderUUID"] + "\"," + row["payMethod"] + ",\"" + sender + "\")' href='javascript:void(0)'>继续</a></li>";
        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showSendBack(" + row["docId"] + ",5,\"\",\"" + sender + "\")' href='void(0)'>退回</a></li>"
    }
    //5: 待他人签
    else if (type == 5) {
        //判断本人是否是发送者(顺序签)
        if (accountUUID == row["sends"][0]["senderUUID"]) {
            appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:operationDoc(" + row["docId"] + ",3,\"\");'>催签</a></li>";
            appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showEventChoose(\"您确认结束此文件的签署吗？一旦关闭则无法恢复。\",\"operationDoc(" + row["docId"] + ",6)\")'>关闭</a></li>";
        }
    }
    //10:
    else if (type == 10) {
        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showBackReason(\"" + reason + "\", \"\")'>退回原因</a></li>"
        //被退回且是收件人可以查看退回原因、重新签署、关闭
        if ((accountUUID != row["sendbacker"]) &&
            (accountUUID == row["sends"][0]["senderUUID"])) {
            appendHtml += "<li><a class='' onclick='javascript:writeContractSubmit(" + row["docId"] + ", " + JSON.stringify(row["sends"]) + ",\"change\");' href='javascript:void(0)'>重新签署</a></li>"
            appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showEventChoose(\"您确认结束此文件的签署吗？一旦关闭则无法恢复。\",\"operationDoc(" + row["docId"] + ",6)\")'>关闭</a></li>"
        }
    }
    else if (type == 11) {
        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showEventChoose(\"确认删除文档\", \"deleteDoc(" + row["docId"] + ")\");'>删除</a></li>";
    } else if (type == 12) {
        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showBackReason(\"" + reason + "\", \"\")'>退回原因</a></li>"

    } else if (type == 13) {

        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showBackReason(\"" + reason + "\", \"\")'>退回原因</a></li>"
        if ((accountUUID != row["sendbacker"]) &&
            (accountUUID == row["sends"][0]["senderUUID"])) {
            appendHtml += "<li><a class='' onclick='javascript:writeContractSubmit(" + row["docId"] + ", " + JSON.stringify(row["sends"]) + ",\"change\");' href='javascript:void(0)'>重新签署</a></li>"
            appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:showEventChoose(\"您确认结束此文件的签署吗？一旦关闭则无法恢复。\",\"operationDoc(" + row["docId"] + ",6)\")'>关闭</a></li>"
        }
    }

    //1&3草稿和云文件没有文档流程
    if (!(type == 1 || type == 3)) {
        appendHtml += "<li><a class='' href='javascript:void(0)' onclick='javascript:signLog(" + row["docId"] + ", \"\")'>文档流程</a></li></ul></div>";
    }
    return appendHtml;
}